package com.qf.controller;
/*
 *@Description:
 *@author:刘哥
 *@Date:21:49 2022/6/29
 */

import com.alibaba.fastjson.JSON;

import com.qf.pojo.TbUser;

import com.qf.pojo.WeiXinResult;
import com.qf.service.OrderService;
import com.qf.service.impl.OrderServiceImpl;
import com.qf.utils.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * projectName:myxiaomi
 * author:刘哥
 * time:2022/8/19 10:49
 * description:
 */
@WebServlet("/paySuccess")
public class PaySuccessServlet extends HttpServlet {
//    修改数据库支付完后的订单状态
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
//        判断用户是否登录
        TbUser user = (TbUser) request.getSession().getAttribute("user");
        if (user == null) {
           response.sendRedirect(request.getContextPath()+"/login.jsp");//重定向
           return;
        }
//       获取前端数据
        String result = request.getParameter("result");
        if(StringUtil.isEmpty(result)){
            response.sendRedirect(request.getContextPath()+"/login.jsp");
            return;
        }
//        处理结果   支付完后修改状态
//        使用JSON处理数据，将前端的数据给实体类                     类对象
        WeiXinResult weiXinResult = JSON.parseObject(result,WeiXinResult.class);
        String oid = weiXinResult.getResult().getOut_trade_no();//获取订单号
//        支付成功后 才能修改订单状态   微信 支付的服务器和  项目服务器  不是一个
//        getResult_code()支付的状态
        if(weiXinResult.getResult().getResult_code().equals("SUCCESS")){
//            支付成功修改状态
            //类型 0为页面重定向,1为点对点服务器通信,因为是 localhost 地址,无法使用1
            if (weiXinResult.getType()== 0) {
                OrderService orderService=new OrderServiceImpl();
                orderService.udateStatus(oid,2);//oid，订单号，状态2
                request.setAttribute("msg","支付成功,傻逼商家忽悠你说尽快发货...");
                request.getRequestDispatcher("/message.jsp").forward(request,response);//转发

            }else if(weiXinResult.getType()==1){
                System.out.println("点对点通讯");
            }

        }else{
            request.setAttribute("msg","订单支付失败");
            request.getRequestDispatcher("/message.jsp").forward(request,response);//转发
        }


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
